package com.codebox.common.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.codebox.common.R;
import com.codebox.common.util.ToastUtils;
import com.codebox.common.view.DividerDecoration;
import com.codebox.common.view.EmptyLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 刷新基类
 *
 * @author 李立
 * @date 2018/12/7
 */
public abstract class BaseSmartRefreshFragment<T> extends Fragment implements
        SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener {

    protected BaseQuickAdapter mAdapter;

    protected ArrayList<T> mList;

    private EmptyLayout mEmptyLayout;
    private SwipeRefreshLayout mSwipeLayout;
    private RecyclerView mRecyclerView;

    protected int mPageNo;
    private static final int PAGE_SIZE = 20;

    protected int getLayoutId() {
        return R.layout.activity_base_refresh_layout;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(getLayoutId(), null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    private void initView(View view) {
        mList = new ArrayList<>();

        mEmptyLayout = view.findViewById(R.id.emptyLayout);
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mSwipeLayout = view.findViewById(R.id.swipe_refresh_layout);
        mSwipeLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setOnRefreshListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        if (needDividerDecoration()) {
            mRecyclerView.addItemDecoration(new DividerDecoration(getActivity(),
                    getResources().getColor(R.color.y_line_divider), 1f));
        }
    }

    /**
     * 是否需要上拉加载
     */
    protected boolean needLoadMore() {
        return true;
    }

    /**
     * 是否需要分割线
     */
    protected boolean needDividerDecoration() {
        return true;
    }

    protected RecyclerView getBaseRecyclerView() {
        return mRecyclerView;
    }

    /**
     * 设置适配器 在子类中调用
     */
    protected void setAdapter(BaseQuickAdapter adapter) {
        mAdapter = adapter;
        mAdapter.setOnItemClickListener(this);

        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
        mAdapter.setEnableLoadMore(needLoadMore());

        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onRefresh() {
        mPageNo = 0;
        getData();
    }

    @Override
    public void onLoadMoreRequested() {
        ++mPageNo;
        getData();
    }

    /**
     * 请求数据的业务在子类中实现
     */
    protected abstract void getData();

    /**
     * 拿到数据的状态集合
     *
     * @param listTemp 请求拿到的数据
     * @param status   请求数据得到的状态
     * @return 状态数组
     */
    private boolean[] getCondition(List<T> listTemp, Status status) {
        //条件
        boolean[] b = new boolean[2];
        //请求成功条件
        b[0] = (status == Status.SUCCESS);
        //显示空数据界面的条件
        b[1] = ((listTemp != null && listTemp.size() == 0) || (listTemp == null));
        return b;
    }

    /**
     * 暂无内容调用
     */
    private void setEmptyTips() {
        mEmptyLayout.setNoDataContent(getEmptyTips());
        mEmptyLayout.setErrorType(EmptyLayout.NO_DATA);
    }

    /**
     * 默认没有数据的提示文本（“暂无内容”）
     */
    protected String getEmptyTips() {
        return "暂无内容";
    }

    /**
     * 拿到数据后的处理，在子类getData()数据回调后调用。
     *
     * @param listTemp 数据列表
     * @param status   请求的状态
     */
    protected void dealWithData(List<T> listTemp, Status status) {

        mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        boolean[] condition = getCondition(listTemp, status);

        //请求成功
        if (condition[0]) {

            if (mPageNo == 0 && condition[1]) {
                mSwipeLayout.setRefreshing(false);
                setEmptyTips();
                return;
            }

            if (mPageNo == 0) {
                mList.clear();
                mSwipeLayout.setRefreshing(false);
            }

            if (mPageNo == 0 && (listTemp == null || listTemp.size() == 0)) {
                setEmptyTips();
                mAdapter.notifyDataSetChanged();
                mSwipeLayout.setRefreshing(false);
                return;
            }

            if (listTemp != null) {
                mList.addAll(listTemp);
            }

            mAdapter.notifyDataSetChanged();
            if (listTemp == null || listTemp.size() < PAGE_SIZE) {
                mSwipeLayout.setRefreshing(false);
                mAdapter.loadMoreComplete();
                return;
            }

            mAdapter.loadMoreComplete();

        }
        //请求失败
        else {
            if (mList == null || mList.size() == 0) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            } else {
                ToastUtils.showInfo(getString(R.string.error_network_request));
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
            mSwipeLayout.setRefreshing(false);
        }

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }
}
